/*
 * @Description: 线路收藏的工具类
 * @Author: yingying.fan
 * @Date: 2019-05-27 14:51:10
 * @Last Modified by: yingying.fan
 * @Last Modified time: 2019-06-14 18:24:50
 */
const COLLECTED_LINE_KEY = 'fegiuSDGIbkjd'

/**
 * 设置收藏状态
 * @param {Boolean} isCollected 是否收藏
 * @param {String} routeId 线路id
 * @param {Number} direction 方向
 * @param {Number} routeName 线路名称
 * @param {Number} startStation 首站
 * @param {Number} endStation 末站
 * @param {Number} startTime 首班车
 * @param {Number} endTime 末班车
 * @param {Number} price 票价
 */
function setRouteCollected(
  isCollected,
  routeId,
  direction,
  routeName,
  startStation,
  endStation,
  startTime,
  endTime,
  price
) {
  let routeArray = window.localStorage.getItem(COLLECTED_LINE_KEY)
  routeArray = JSON.parse(routeArray)
  if (routeArray == null) routeArray = []
  if (isCollected) {
    for (let i = 0; i < routeArray.length; i++) {
      if (
        // eslint-disable-next-line
        routeArray[i].SUBROUTE_ID == routeId &&
        // eslint-disable-next-line
        routeArray[i].TYPE == direction
      ) {
        routeArray.splice(i, 1)
        routeArray = JSON.stringify(routeArray)
        console.log('~~~~线路收藏列表', routeArray)
        window.localStorage.setItem(COLLECTED_LINE_KEY, routeArray)
        break
      }
    }
  } else {
    let map = {}
    map.SUBROUTE_ID = parseInt(routeId)
    map.SUBROUTE_NAME = routeName
    map.BUS_START_STATION = startStation
    map.BUS_END_STATION = endStation
    map.START_TIME = startTime
    map.END_TIME = endTime
    map.PRICE = price
    map.TYPE = direction
    map.GOTO_URL =
      'Line.html?BUS_DIRECTION=' +
      direction +
      '&NAME=' +
      routeName +
      '&ID=' +
      routeId
    routeArray.push(map)
    routeArray = JSON.stringify(routeArray)
    window.localStorage.setItem(COLLECTED_LINE_KEY, routeArray)
  }
  return Promise.resolve(!isCollected)
}

/**
 * 判断该线路是否收藏
 * @param {String} routeId 线路id
 * @param {Number} direction 方向
 */
function isRouteCollected(routeId, direction) {
  let lineCollection = window.localStorage.getItem(COLLECTED_LINE_KEY)
  lineCollection = JSON.parse(lineCollection)
  let isCollected = false
  if (lineCollection) {
    for (let i = 0; i < lineCollection.length; i++) {
      // 判断要用双等于
      if (
        // eslint-disable-next-line
        lineCollection[i].SUBROUTE_ID == routeId &&
        // eslint-disable-next-line
        lineCollection[i].TYPE == direction
      ) {
        isCollected = true
        break
      }
    }
  }
  return Promise.resolve(isCollected)
}

/**
 * 获取收藏线路列表
 */
function getColletctedRouteList() {
  let routeArray = window.localStorage.getItem(COLLECTED_LINE_KEY)
  try {
    routeArray = JSON.parse(routeArray)
  } catch (error) {
    routeArray = []
  }
  return Promise.resolve(routeArray)
}

export { setRouteCollected, isRouteCollected, getColletctedRouteList }
